package com.yizhang.disruptor.producer;

import com.lmax.disruptor.RingBuffer;
import com.yizhang.disruptor.entity.OrderEvent;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * @Author: yi.zhang
 * @CreateTime: 2025-05-21 13:11:37
 * @Description: 订单事件生产者
 */
public class OrderEventProducer {

    private final RingBuffer<OrderEvent> ringBuffer;

    public OrderEventProducer(RingBuffer<OrderEvent> ringBuffer) {
        this.ringBuffer = ringBuffer;
    }

    public void onData(String userId, BigDecimal price) {
        //获取下一个可插入序列
        long sequence = ringBuffer.next();

        //获取这个位置上的事件对象
        try {
            OrderEvent orderEvent = ringBuffer.get(sequence);
            orderEvent.setUserId(userId);
            orderEvent.setPrice(price);
            orderEvent.setStatus("待支付");
            orderEvent.setOrderId(UUID.randomUUID().toString());
        } finally {
            //发布事件
            ringBuffer.publish(sequence);
        }
    }
}
